package gdi1.electricbox.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class FileHandler {

	/**
	 * @author Theo
	 * @param fileName
	 * @return serializable object from specified file
	 */
	public static Object loadFromFile(String fileName) {
		InputStream fis = null;
		Object temp = null;
		try {
			fis = new FileInputStream(fileName);
			ObjectInputStream ois = new ObjectInputStream(fis);
			temp = ois.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.err.println(e);
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
				System.err.println(e);
			}
		}
		return temp;
	}

	/**
	 * Qelle:
	 * http://www.javadb.com/writing-objects-to-file-with-objectoutputstream
	 * 
	 * @author Theo
	 * @param fileName
	 * @throws IOException
	 */
	public static void writeToFile(Object obj, String fileName)
			throws IOException {
		ObjectOutputStream o = null;
		try {
			o = new ObjectOutputStream(new FileOutputStream(fileName));
			o.writeObject(obj);
		} catch (FileNotFoundException e) {
			System.err.println("file not found");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (o != null) {
					o.flush();
					o.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
